﻿namespace MyCompany.MyApplication {
	using System;
	using System.IO;
	using System.Reflection;
	using System.Windows;

	using SolidMvvm;

	using ViewModels;

	using SolidMvvmInterfaces;

	static class Launch {
		static MyApplicationViewModel myApplicationViewModel;

		static WPFApp wpfApp;

		[STAThread]
		public static void Main() {
			try {
				using (wpfApp = new WPFApp(Assembly.GetExecutingAssembly(), false, "/MyApplication;component/LaunchResourceDictionary.xaml"))
					try {
						var mainWindowSettings = SettingDictionary.FromFile(Path.Combine(wpfApp.ApplicationDataFolderPath, "MainWindow.json"));

						using (var window = new WPFWindow(wpfApp.ApplicationName, mainWindowSettings, new Size(800D, 600D), Path.Combine(wpfApp.ExecutablePath, "App.ico"), WindowState.Normal, true, false, WindowStyle.ThreeDBorderWindow, ResizeMode.CanResizeWithGrip, false, false, WPFWindow_CloseRequested))
							using (myApplicationViewModel = new MyApplicationViewModel(wpfApp, window.LeftStatusBarItemSnapInPoints, window.CenterStatusBarItemSnapInPoints, window.RightStatusBarItemSnapInPoints, wpfApp, MyApplicationViewModel_ApplicationExitRequestedDelegate))
								try {
									window.ClientContent = myApplicationViewModel;
									window.IsVisible = true;
									wpfApp.Run();
								}
								catch {
									myApplicationViewModel.SuppressCanClose();
									throw;
								}
					}
					catch (Exception exception) {
						wpfApp.ReportMessage(exception.Message, exception.ToString(), MessageType.Display);
					}
			}
			catch (Exception exception) {
				MessageBox.Show(exception.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		// The request came from a view model, not from the window.
		static void MyApplicationViewModel_ApplicationExitRequestedDelegate(IApplicationViewModelBase sender) {
			if (myApplicationViewModel.CanClose())
				wpfApp.Shutdown(0);
		}

		// The request to close came from the window itself, not a view model.
		static void WPFWindow_CloseRequested(WPFWindow sender) {
			if (myApplicationViewModel.CanClose())
				wpfApp.Shutdown(0);
		}
	}
}
